import { ElButton, ElForm, ElFormItem, ElInput, FormInstance, FormRules } from "element-plus"
import { cloneDeep } from "lodash-es"
import { Dialog } from "~/src/api/interface"
import { System } from "~/src/api/interface/system"
import { createFrontDeskMenuAPI, editFrontDeskMenuAPI } from "~/src/api/system"
import VabDialog from '/@vab/components/VabDialog/index.vue'

export type AddDialogExpose = {
  setParams: (data: Dialog<System.FrontDeskMenu>) => void;
};
export default defineComponent({
  name: "AddDialog",
  props: {
    title: {
      type: String,
      default:""
    },
    data: {

    }
  },
  emits: ["onOk"],
  setup(props, {  expose,emit}) {
    // 子组件暴露的方法类型
type AddDialogExpose = {
  setParams: (data: Dialog<System.FrontDeskMenu>) => void;
};
    const formdata = ref<Dialog<System.FrontDeskMenu>>({data:{code:"",name:""},title:"",visible:false})
    const setParams = (data:Dialog<System.FrontDeskMenu>) => {
        formdata.value.title = data.title
      formdata.value.data = cloneDeep(data.data)
      formdata.value.visible = true
    }
    const rules = reactive<FormRules>({
      name:[{required:true,message:'请输入名称',trigger:'blur'}],
      code:[{required:true,message:'请输入编码',trigger:'blur'}]
    })
    const formRef = ref<FormInstance>()
    watch(() => formdata.value.visible, (val) => {
      if (!val) {
        formRef.value?.resetFields()
      }
    })

    const onSubmit = async () => {
      await formRef.value?.validate()
      if (formdata.value.data.id) {
        await editFrontDeskMenuAPI(formdata.value.data)
      } else {
        await createFrontDeskMenuAPI(formdata.value.data)
      }
      emit("onOk")
      formdata.value.visible = false
}

    expose<AddDialogExpose>({setParams})
    return () =>

    <VabDialog v-model:modelValue={formdata.value.visible} title={formdata.value.title + '前台菜单'} width="500"
    v-slots={{ footer: () => (
      <>
        <ElButton type="primary" onClick={onSubmit}>保存</ElButton>
        <ElButton onClick={()=> formdata.value.visible = false}>取消</ElButton>
      </>
        )
        }}
      >
      {
      <ElForm ref={formRef} rules={rules} model={formdata.value.data} label-width={80}>
        <ElFormItem prop={'name'} label="名称">
        <ElInput v-model={formdata.value.data.name}></ElInput>
        </ElFormItem>
        <ElFormItem prop={'code'} label="编码">
        <ElInput v-model={formdata.value.data.code}></ElInput>
        </ElFormItem>
      </ElForm>
}
    </VabDialog >

  }
})
